package com.apache.funds.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.apache.action.ActionSupport;
import com.apache.api.entity.BaseEntity;
import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.Validator;
import com.apache.database.model.Page;
import com.apache.funds.common.FundsUtil;
import com.apache.funds.common.NumberUtil;
import com.apache.funds.entity.SvmUser;
import com.apache.funds.vo.UserFundsVo;
import com.apache.tools.StrUtil;

/**  
 * 管理action 
 */
@Controller
@RequestMapping("funds/admin")
public class FundsAdminAction extends ActionSupport<BaseEntity> {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 跳转到钱包用户页面
	 */
	@RequestMapping("toUserList.action")
	public ModelAndView toUserList(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("funds/funds-user-list");
		return view;
	}

	/**
	 * 钱包用户数据查询
	 */
	@RequestMapping("userList.action")
	@ResponseBody
	public Object userList(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(value = "page") int page, @RequestParam(value = "rows") int rows) {
		ParamsVo<SvmUser> vo = new ParamsVo<SvmUser>();
		Map<String, Object> fundsMap = WebUtils.getParametersStartingWith(request, "");
		fundsMap.put("pageSize", rows);
		fundsMap.put("pageIndex", page);
		ResultEntity entity = FundsUtil.selectFundsUserList(fundsMap);
		Map mapData = new HashMap();
		if ("true".equals(entity.getResult()) && !"false".equals(entity.getEntity())) {
			Page pageList = (Page) entity.getEntity();
			mapData.put("total", Integer.valueOf(pageList.getCount()));
			mapData.put("rows", pageList.getPageObjects());
		}
		return mapData;
	}

	/**
	 * 账务余额查询 
	 */
	@RequestMapping("queryYe.action")
	@ResponseBody
	public String queryYe(String userEname, HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		//封装参数
		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("userId", userEname);

		//案例一：后台调用案例
		UserFundsVo userFundsVo = FundsUtil.selectFundsMyMoneyByCache(userEname);
		if (userFundsVo != null) {
			json.put("isok", "T");
			json.put("msg", "查询完成");
		} else {
			json.put("isok", "F");
			json.put("msg", "查询失败");
		}
		json.put("funds", userFundsVo);
		showJson(json, response);
		return null;
	}

	/**
	 * 跳转到用户资金操作流水页面
	 */
	@RequestMapping("toFlowList.action")
	public ModelAndView toFlowList(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("funds/funds-flow-list");
		return view;
	}

	/**
	 * RPC调用交易所账户资金流水明细查询方法
	 */
	@RequestMapping("flowList.action")
	@ResponseBody
	public Object flowList(HttpServletRequest request, String page, String rows) {

		Map<String, Object> fundsMap = new HashMap<String, Object>();
		//		String userEname = platformFundsId();//读取配置文件中交易所平台账户

		Map<String, Object> filterMap = WebUtils.getParametersStartingWith(request, "");
		String userEname = String.valueOf(filterMap.get("userEname"));

		//查询明细
		fundsMap.put("pageSize", Validator.getDefaultStr(rows, "10"));
		fundsMap.put("pageIndex", Validator.getDefaultStr(page, "1"));
		fundsMap.put("userid", Validator.getDefaultStr(userEname, ""));
		//		String actype = String.valueOf(fundsMap.get("actype"));
		//		if (StrUtil.isNotNull(actype)) {
		//			params.put("actype", getSqlInStr(actype));
		//		}
		Page pageList = new Page();
		//获取结果
		ResultEntity entity = FundsUtil.selectFundsFlowing(fundsMap);

		if (entity != null && "true".equals(entity.getResult()) && entity.getEntity() != null) {
			pageList = (Page) entity.getEntity();
		} else {
			System.out.println("未获取到对象：" + entity);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", pageList.getCount());
		map.put("rows", pageList.getPageObjects());
		return map;
	}

	/**
	 *入
	 */
	@RequestMapping({ "sendIn.action" })
	@ResponseBody
	public String sendIn(String userEname, String amount, HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		long amounLong = Math.round(NumberUtil.mul(Double.parseDouble(amount), 100, 2));

		//拼接参数
		Map<String, String> prarmMap1 = new HashMap<String, String>();
		prarmMap1.put("tradeType", "FINT");//定值
		prarmMap1.put("userId", userEname);//账号
		prarmMap1.put("amt", String.valueOf(amounLong));//操作金额

		//添加参数组
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		list.add(prarmMap1);

		//补充参数
		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("funds", list);
		fundsMap.put("actionId", "I-" + String.valueOf(new Date().getTime()));//业务流水号
		fundsMap.put("remark", "资金账户充值");//业务描述

		String isok = "F", msg = "充值失败";
		ResultEntity entity = FundsUtil.doFunds(fundsMap.get("remark").toString(), fundsMap);
		if ("true".equals(entity.getResult()) && "true".equals(String.valueOf(entity.getEntity()))) {
			isok = "T";
			msg = entity.getMessage();
		}
		json.put("isok", isok);
		json.put("msg", msg);
		showJson(json, response);
		return null;
	}

	/**
	 * 出
	 */
	@RequestMapping({ "sendOut.action" })
	@ResponseBody
	public String sendOut(String userEname, String amount, HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		//拼接参数
		Map<String, String> prarmMap1 = new HashMap<String, String>();
		prarmMap1.put("tradeType", "FOUT");//定值
		prarmMap1.put("userId", userEname);//账号
		prarmMap1.put("amt", amount);//操作金额

		//添加参数组
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		list.add(prarmMap1);

		//补充参数
		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("funds", list);
		fundsMap.put("actionId", "O-" + String.valueOf(new Date().getTime()));//业务流号
		fundsMap.put("remark", "测试出金提现");//业务描述
		ResultEntity entity = FundsUtil.doFunds(fundsMap.get("remark").toString(), fundsMap);

		json.put("isok", entity);

		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 冻结
	 */
	@RequestMapping({ "sendFreeze.action" })
	@ResponseBody
	public String sendFreeze(String userEname, String amount, HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		//拼接参数
		Map<String, String> prarmMap1 = new HashMap<String, String>();
		prarmMap1.put("tradeType", "PBOD");//定值
		prarmMap1.put("userId", userEname);//账号
		prarmMap1.put("amt", amount);//操作金额

		//添加参数组
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		list.add(prarmMap1);

		//补充参数
		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("funds", list);
		fundsMap.put("actionId", "F-" + String.valueOf(new Date().getTime()));//业务流水号
		fundsMap.put("remark", "测试冻结");//业务描述
		ResultEntity entity = FundsUtil.doFunds(fundsMap.get("remark").toString(), fundsMap);

		json.put("isok", entity);

		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 解冻
	 */
	@RequestMapping({ "sendFreezeUn.action" })
	@ResponseBody
	public String sendFreezeUn(String userEname, String amount, HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		//拼接参数
		Map<String, String> prarmMap1 = new HashMap<String, String>();
		prarmMap1.put("tradeType", "CBOD");//定值
		prarmMap1.put("userId", userEname);//账号
		prarmMap1.put("amt", amount);//操作金额

		//添加参数组
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		list.add(prarmMap1);

		//补充参数
		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("funds", list);
		fundsMap.put("actionId", "U-" + String.valueOf(new Date().getTime()));//业务流水号
		fundsMap.put("remark", "测试解冻");//业务描述
		ResultEntity entity = FundsUtil.doFunds(fundsMap.get("remark").toString(), fundsMap);

		json.put("isok", entity);

		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 冻结资金交割给平台(买方冻结→交易所有效)
	 * 常用于如下情况：
	 * 1）一级发售认购交割（从冻结给平台）
	 * 2）保证金交给平台（从冻结给平台）
	 */
	@RequestMapping({ "sendDealFBDV.action" })
	@ResponseBody
	public String sendDealFBDV(String fromUserId, String toUserId, String amount, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject json = new JSONObject();

		//拼接参数
		Map<String, String> prarmMap1 = new HashMap<String, String>();
		prarmMap1.put("tradeType", "FBDV");//定值
		prarmMap1.put("fromUserId", fromUserId);//付款方账户
		prarmMap1.put("toUserId", toUserId);//传入平台账号
		prarmMap1.put("amt", amount);//操作金额

		//添加参数组
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		list.add(prarmMap1);

		//补充参数
		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("funds", list);
		fundsMap.put("actionId", "FBDV-" + String.valueOf(new Date().getTime()));//业务流水号
		fundsMap.put("remark", "冻结资金交割给平台");//业务描述
		ResultEntity entity = FundsUtil.doFunds(fundsMap.get("remark").toString(), fundsMap);

		json.put("isok", entity);

		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 有效资金互相交割(A有效→B有效)
	 * 常用于如下情况：
	 * 1）情况1：买方有效给交易所有效（fromUserId=买方，toUserId=交易所）
	 * 2）情况2：交易所有效给买方有效（fromUserId=交易所，toUserId=买方）
	 */
	@RequestMapping({ "sendDealFADV.action" })
	@ResponseBody
	public String sendDealFADV(String fromUserId, String toUserId, String amount, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject json = new JSONObject();

		//拼接参数
		Map<String, String> prarmMap1 = new HashMap<String, String>();
		prarmMap1.put("tradeType", "FADV");//定值
		prarmMap1.put("fromUserId", fromUserId);//付款方账户
		prarmMap1.put("toUserId", toUserId);//收款方账户
		prarmMap1.put("amt", amount);//操作金额

		//添加参数组
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		list.add(prarmMap1);

		//补充参数
		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("funds", list);
		fundsMap.put("actionId", "FADV-" + String.valueOf(new Date().getTime()));//业务流水号
		fundsMap.put("remark", "测试有效资金互相交割");//业务描述
		ResultEntity entity = FundsUtil.doFunds(fundsMap.get("remark").toString(), fundsMap);

		json.put("isok", entity);

		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 开户
	 */
	@RequestMapping({ "sendOpenAccount.action" })
	@ResponseBody
	public String sendOpenAccount(String userEname, HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		//拼接参数
		/**
		 * 参数map的key说明:<br>
		 * userEname,userCname<br>
		 * certCode,certType,mobile,contactuser,contactAddress
		 */
		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("userEname", userEname);//此项必填项

		//以下根据实际情况选择传入
		fundsMap.put("userCname", "单位名称-" + userEname);
		fundsMap.put("certType", "P");//证件类型：【A：身份证，P：组织代码，R：营业执照，O：统一社会信用代码，Z：其他】
		fundsMap.put("certCode", "12345678-9");//证件号码
		fundsMap.put("mobile", "13267890981");//手机号
		fundsMap.put("contactuser", "张三");//联系人
		fundsMap.put("contactAddress", "北京市海淀区知春路");//地址

		ResultEntity entity = FundsUtil.doFundsOpenAccount(fundsMap);

		json.put("isok", entity);

		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 登录：资金账户或口令校验
	 */
	@RequestMapping({ "sendAccountLogin.action" })
	@ResponseBody
	public String sendAccountLogin(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("userEname", String.valueOf(request.getParameter("userEname")));//此项必填项
		fundsMap.put("password", String.valueOf(request.getParameter("pass")));//此项必填项

		ResultEntity entity = FundsUtil.doFundsAccountLogin(fundsMap);

		json.put("isok", entity);
		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 资金账户口令更换
	 */
	@RequestMapping({ "sendAccountPass.action" })
	@ResponseBody
	public String sendAccountPass(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		Map<String, Object> fundsMap = new HashMap<String, Object>();
		fundsMap.put("userEname", String.valueOf(request.getParameter("userEname")));//此项必填项
		fundsMap.put("passold", String.valueOf(request.getParameter("passold")));//此项必填项
		fundsMap.put("passnew", String.valueOf(request.getParameter("passnew")));//此项必填项

		ResultEntity entity = FundsUtil.doFundsAccountPass(fundsMap);

		json.put("isok", entity);
		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 刷新用户缓存（重新读库统计）
	 */
	@RequestMapping({ "sendHc.action" })
	@ResponseBody
	public String sendHc(String userEname, HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		//1.先刷新
		if (StrUtil.isNotNull(userEname)) {
			FundsUtil.doFundsCache(userEname);
		}
		json.put("isok", "T");

		//2.再次查询
		System.out.println("刷新完成完成后，可以再次查询下余额缓存");
		json.put("msg", "刷新完成后：" + FundsUtil.selectFundsMyMoneyByCache(userEname));

		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 定时器要调用的，资金日终结果设置（期初+发生）
	 */
	@RequestMapping({ "timeTaskBalance.action" })
	@ResponseBody
	public String timeTaskBalance(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		String dateStr = request.getParameter("dateStr");

		//外部定时插件参照调用方式
		ResultEntity entity = FundsUtil.doFundsTimeTaskBalance(dateStr);

		json.put("isok", entity);
		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	/**
	 * 查询我的虚拟账户信息
	 */
	@RequestMapping({ "queryMyAccount.action" })
	@ResponseBody
	public String queryMyAccount(String userEname, HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();

		ResultEntity entity = FundsUtil.selectFundsMyAccount(userEname);

		json.put("result", entity);
		System.out.println("返回结果:" + json);
		showJson(json, response);
		return null;
	}

	@Override
	protected Object data(HttpServletRequest arg0, String arg1, String arg2) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected BaseManager<BaseEntity> getBaseManager() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String getPrefix() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 返回json数据
	 * @author Administrator  
	 * @param jvo
	 * @param response
	 * @return   
	 * @update 2015-4-10
	 */
	public static String showJson(JSONObject jvo, HttpServletResponse response) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(jvo.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
